package db

import (
	_ "github.com/go-sql-driver/mysql"
)

// 获取产品
type Product struct {
	Id        	int	  `json:"id"`
	Title 		string		`json:"title"`
	Desc 		string		`json:"desc"`
	Weight 		string		`json:"weight"`
	ImgSrc		string		`json:"imgSrc"`
	Img			string		`json:"img"`
	ImgId		int		`json:"imgId"`
	QrSrc		string	`json:"qrSrc"`
	Qrcode		string	`json:"qrcode"`
	QrcodeId  	int		`json:"qrcodeId"`
}
func GetProduct(page int,limit int)(as []Product,err error){
	rows, err := ulwebsiteDb.Query(`
	SELECT
	    x.id,ifnull(x.title,""),ifnull(x.desc,""),ifnull(x.weight,""),ifnull(e.src,"") as imgSrc,ifnull(e.title,"") as img,e.id as imgId,ifnull(w.src,"") as qrSrc,ifnull(w.title,"") as qrcode,w.id as qrcodeId
    FROM
        product x
        LEFT JOIN imgfile e on e.id = x.imgId 
		LEFT JOIN imgfile w on w.id = x.qrcodeId
	ORDER BY
		weight desc
	LIMIT
		?,?
	`,page*limit,limit)
	if err != nil {
		return
	}
	defer rows.Close()
	as = make([]Product,0)
	for rows.Next() {
		var a Product
		err = rows.Scan(&a.Id,&a.Title,&a.Desc,&a.Weight, &a.ImgSrc,&a.Img,&a.ImgId,&a.QrSrc,&a.Qrcode,&a.QrcodeId)
		if err != nil {
			return
		}
		as = append(as, a)
	}
	return
}

//发布产品
func PostProduct(title string,desc string,weight string,imgId string,qrcodeId string)(id int64,err error){
	tx, err := ulwebsiteDb.Begin()
	if err != nil {
		return
	}
	defer tx.Commit()
	rows, err := tx.Exec("insert into product(title,`desc`,`weight`,imgId,qrcodeId) values(?,?,?,?,?)",title,desc,weight,imgId,qrcodeId)
	if err != nil {
		tx.Rollback()
		return
	}
	id,err = rows.LastInsertId()
	if err != nil {
		return
	}
	return
}
//修改产品
func EditProduct(title string,desc string,weight string,imgId string,qrcodeId string,uid string)(id int64,err error){
	tx, err := ulwebsiteDb.Begin()
	if err != nil {
		return
	}
	defer tx.Commit()
	rows, err := tx.Exec("UPDATE product SET title=?,`desc`=?,`weight`=?,imgId=?,qrcodeId=? WHERE id=?",title,desc,weight,imgId,qrcodeId,uid)
	if err != nil {
		tx.Rollback()
		return
	}
	id,err = rows.LastInsertId()
	if err != nil {
		return
	}
	return
}
//删除产品
func DelProduct(uid string)(id int64,err error){
	tx, err := ulwebsiteDb.Begin()
	if err != nil {
		return
	}
	defer tx.Commit()

	rows, err := tx.Exec("DELETE FROM product WHERE id=?",uid)
	if err != nil {
		tx.Rollback()
		return
	}
	id,err = rows.LastInsertId()
	if err != nil {
		return
	}
	return
}
